3<%@ page import="ar.com.photo_admin.domain.Event"%>
<!doctype html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
	xmlns:fb="http://www.facebook.com/2008/fbml">
	
	<!-- CSS to style the Guidely feature -->
	
<head>
<meta name="layout" content="main">
</head>
<body>
	<link rel="stylesheet"
		href="${resource(dir:'css',file:'guidely.css')}" type="text/css" />

	<div class="page-header">
		<h1><g:message code="share.albums"/></h1>
	</div>
	
	<g:if test="${flash.message}">
		<div class="alert alert-success">
			<a class="close" data-dismiss="alert">×</a>
			${flash.message}
		</div>
	</g:if>
	
	<g:if test="${flash.error}">
		<div class="alert alert-error">
			<a class="close" data-dismiss="alert">×</a>
			${flash.error}
		</div>
	</g:if>

	<div class="titleDescription">
	  <p><g:message code="share.titleDescription"/></p>
	</div>
		
	<g:if test="${event}">
	
		<div class="form-horizontal">
			<div class="control-group">
				<label class="control-label" for="eventName"><g:message
						code="event" /></label>
				<div class="controls">
					<select id="eventNamesSelector"></select>
				</div>
			</div>
		</div>
		
		<div id="eventAlbumTokenErrors"></div>

		
		<div id="albumsContainer" class="row">

			<g:if test="${event?.albums}">
				<g:each in="${event.albums}" var="album">
				
					<div id="albumContainer${album?.id}" class="span3 gridElement">
						<p>
							${album?.name}
						</p>
						
						<div class="gridImage">
							<img src="${album.coverPhoto ? album?.coverPhoto?.getPublishedThumbnailMediumUrl() : resource(dir:'images', file: 'defaultImage.jpg')}"
									class="gridMediumImage img-rounded" onclick="selectAlbum('albumCheckBox${album?.id}');"></img>
						</div>
						<g:checkBox id="albumCheckBox${album?.id}" class="centerCheckbox" name="albumCheckBox${album?.id}" value=""/>				
					</div>

				</g:each>
			</g:if>
			<g:else>
				<div class="alert alert-warning">
					<a class="close" data-dismiss="alert">×</a>
					<div class="message">
						<g:message code="share.eventWithNoAlbums" />
					</div>
				</div>
			</g:else>
		</div>

		<g:form id="createTokenForm" name="createTokenForm"
			controller="eventAlbumToken" action="generateToken">
			<g:hiddenField name="eventId" value="${event?.id}" />
			<g:hiddenField id="hiddenTokenAlbumIds" name="selectedAlbumsIds"
				value="" />
		</g:form>

		<div class="btn-group">
			<button id="generateTokenButton" class="btn btn-success">
				<g:message code="share.generate" />
			</button>
			<button id="btnHelp" class="btn btn-info " ><g:message code="help" /></button>
		</div>
				
		<g:render template="tokenAlbumsController" />	
		<g:javascript src="guidely.js" />

		<script type="text/javascript">
		$(document).ready(function() {
		
			tokenAlbumsController = new TokenAlbumsController(${event?.id})
			
			/*
			 * Combo box to select event
			 */
			var jsonEvents = '${eventsMap}';
        	var events = jQuery.parseJSON(jsonEvents);
        	        			
			$.each(events, function(name, id) { 
				$("<option value='" + id + "'>" + name + "</option>").appendTo("#eventNamesSelector");
			});
			
			$("#eventNamesSelector").val(${event?.id})
			
			$("#eventNamesSelector").change(function() {
       	    	var eventId = $("#eventNamesSelector").val();
       	    	var eventAlbumTokenUrl = "${createLink(controller: 'eventAlbumToken', action: 'create')}/" + eventId;
				window.location.replace(eventAlbumTokenUrl);
       	    }); 
       	    
       	    // If there is only one element, the selector is disabled.
       	    if ($("#eventNamesSelector option").length == 1)
       	    	$("#eventNamesSelector").attr('disabled', '');
       	    
    		/*
    		 * Checkboxes to select albums 
    		 */
    		var checkboxes = $('input').filter(function() { return this.id.match(/albumCheckBox*/) })
    		 
       	    checkboxes.change(function() {
       	    	var id = this.id.substr("albumCheckBox".length);
       	    	
       	    	if($(this).is(':checked'))
          		  tokenAlbumsController.addAlbumToToken(id);
         		else
         		  tokenAlbumsController.deleteAlbumFromToken(id);
			});
			
			/*
			 * Generate token submit form
			 */
			 $("#generateTokenButton").click(function() {
			 	tokenAlbumsController.setHiddenFields();
			 	onGenerateToken();
			});			
    	});
    	
    	function onGenerateToken() {
		   	jQuery.ajax({
		                 type: 'POST',
		                 data: $('#createTokenForm').serialize(),        
		                 url: "${createLink(controller: 'eventAlbumToken', action: 'generateToken')}",
		                 async:true,
		                 datatype:"json",
		                 success: function(data,textStatus) { 
		                 		          
							      var position = undefined;
							      		                 		                       		  	
		                          if(data.error){
		                          	$("#eventAlbumTokenErrors").html("<div class='alert alert-error'><a class='close' data-dismiss='alert'>×</a><div class='message'>" + data.error + "</div></div>");
		                          	$("#shareToken").html("");
		                          } 
		                          else{
		                          	 $("#shareToken").html(data);     
		                          	 $("#eventAlbumTokenErrors").html("");
		                          }
		                          
		                          var $target = $('html,body'); 
								  $target.animate({scrollTop: $target.height()}, 1000);
		                 }
		  			});
		  }
		  
		  function selectAlbum(checkboxId) {
		  	var checkbox = jQuery("#" + checkboxId);
		  	checkbox.click();
		  }
	</script>
	
	<script type="text/javascript">
			jQuery(document).ready(function(){
				jQuery('#btnHelp').click(function () {								
					initGuidely();				
				});	
										
			

				function initGuidely(){		

					guidely.clear();
					
					jQuery('#guidelyContainer').remove();
					jQuery('body').append('<div id="guidelyContainer"></div>');
										
					guidely.add ({
						attachTo: '#eventNamesSelector'
						, anchor: 'bottom-middle'
						, title: 'Elija el evento!'
						, text: 'Seleccione el evento que desea compartir. En caso de solo tener acceso a solo un evento, no podrá modificarlo. '
					});

					// Solo agrega el paso en caso de que hayan fotos para agregar					
					if(tokenAlbumsController.getIdFirstAlbum() != null){					
						guidely.add ({
							attachTo: '#'+tokenAlbumsController.getIdFirstAlbum()
							, anchor: 'middle-middle'
							, title: 'Comparta el álbum!'
							, text: 'Seleccione los álbums que quiere compartir presionando el botón '+
									'<input style="margin-bottom: 5px;" type="checkbox" disabled></input>' +
									' ubicado bajo cada álbum'
						});
					}

										
					guidely.add ({
						attachTo: '#generateTokenButton'
						, anchor: 'middle-middle'
						, title: 'Genere las claves!'
						, text: 'Presione el botón para generar las claves para darle a sus conocidos'
					});
					
														
					guidely.init ({ 
						showOnStart: true,
						welcome:false,											
						startTrigger: false });				
				}								
				
								
			});	
	</script>
	
	</g:if>
	<g:else>
		<div class="alert alert-warning">
			<a class="close" data-dismiss="alert">×</a>
			<div class="message">
				<g:message code="share.noEvents" />
			</div>
		</div>
	</g:else>

	<div class="separator"></div>
	<div id="shareToken"></div>
</body>
</html>
